import fs from "node:fs";
import path from "node:path";
import {BaseEvent} from "./event-types";
import { DataPreparation } from "./data-preparation/data-preparation";

const args = process.argv.slice(2);
const directory = args[0] ?? './data';
const target = args[1] ?? './target';

console.log(`Reading from ${directory} and writing to ${target}`);

const files = fs.readdirSync(directory, {withFileTypes: true})
    .filter(d => !d.isDirectory())
    .map(d => d.name);

const fileGroups: FileGroup[] = [{
    groupName: 'Exercise_1',
    files: []
}, {
    groupName: 'Exercise_2',
    files: []
}, {
    groupName: 'Exercise_3',
    files: []
}];

for(let file of files) {
    const group = fileGroups.find(fg => file.startsWith(fg.groupName));
    if(!group) {
        throw new Error(`Could no associate any group to file ${file}`);
    }
    console.log(`Adding file ${file} to group ${group.groupName}`);
    group.files.push(path.join(directory, file));
}

for(let group of fileGroups) {
    const data: BaseEvent[] = [];
    for(let file of group.files) {
        const content = <BaseEvent[]> JSON.parse(fs.readFileSync(file).toString());
        if(file.endsWith(`${group.groupName}.json`)) {
            data.push(...content);
        }
    }
    const preparation = new DataPreparation();

    const preparedData = preparation.prepare(data);

    const serializedData = JSON.stringify(preparedData, undefined, 4);
    const targetFile = path.join(target, `${group.groupName}.json`);
    fs.writeFileSync(targetFile, serializedData);
    console.log(`Succesfully wrote for group ${group.groupName}`);
}

interface FileGroup {
    groupName: string;
    files: string[];
}